//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Icon,
    Button,
    Modal,
    message,
    Divider,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import ProResourceActionCreateForm from './ProResourceActionCreateForm'; //新增表单
import ProResourceActionUpdateForm from './ProResourceActionUpdateForm'; //修改表单
import ProResourceActionViewForm  from './ProResourceActionViewForm'; //查看表单

import styles from './ProResourceActionList.less';
import {getValue} from '@/utils/globalcommon';
const FormItem = Form.Item;



/* eslint react/no-multi-comp:0 */
@connect(({ proresourceaction, loading }) => ({
    proresourceaction,
    loading: loading.models.proresourceaction,
}))

@Form.create()
class ProResourceActionList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
    };


 columns = [

       {
        title: '操作名称',
        dataIndex: 'name',
        key: 'name',
        },        {
        title: '英文名称',
        dataIndex: 'enname',
        key: 'enname',
        },        {
        title: '操作方法',
        dataIndex: 'handler',
        key: 'handler',
        },  	 {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        },   	{
        title: '创建日期',
        dataIndex: 'create_time',
        key: 'create_time',
        }, {
    title: '操作',
    
    render: (text, record) => {
      	return (
	        <Fragment>
							<a onClick={() => this.handleViewModalVisible(true, record)}>查看</a>
							<Divider type="vertical" />
							<a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
					    <Divider type="vertical" />
							{record.key != "000000000000"? ( 							
					    		<a onClick={() => this.handleDeleteRecord(record)}>删除</a>
							): (
								<a onClick={() => message.success('根节点不能删除')}>删除</a>
							)}
			    </Fragment>
	      )
      }
},
];


componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
    	type: 'proresourceaction/query_page_for_proresourceaction',
    });
}



handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
    newObj[key] = getValue(filtersArg[key]);
    return newObj;
}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'proresourceaction/query_page_for_proresourceaction',
        payload: params,
    });
};

previewItem = id => {
    router.push(`/profile/basic/${id}`);
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
    });
    dispatch({
        type: 'proresourceaction/query_page_for_proresourceaction',
        payload: {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};

handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) return;
    switch (e.key) {
        case 'batchremove':
            dispatch({
                type: 'proresourceaction/delete_by_primarykey_for_proresourceaction',
                payload: {
                    id: selectedRows.map(row => row.id),
    			},
			    callback: () => {
			        this.setState({
			            selectedRows: [],
			        });
			    },
    		});
        break;
		case 'batchsend':
        dispatch({
            type: 'proresourceaction/delete_by_primarykey_for_proresourceaction',
            payload: {
                id: selectedRows.map(row => row.id),
    		},
	        callback: () => {
	            this.setState({
	                selectedRows: [],
	            });
	        },
    	});
        break;

    default:
        break;
    }
};

handleSelectRows = rows => {
    this.setState({
        selectedRows: rows,
    });
};


handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

    const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
    };

    this.setState({
        formValues: values,
    });

    dispatch({
        type: 'proresourceaction/query_page_for_proresourceaction',
        payload: values,
    });
});
};

handleModalVisible = flag => {
    this.setState({
        modalVisible: !!flag,
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
        type: 'proresourceaction/insert_for_proresourceaction',
        payload: {
            id: fields.id,
            name: fields.name,
            enname: fields.enname,
            handler: fields.handler,
            icon: fields.icon,
            status: fields.status,
            orderid: fields.orderid,
            memo: fields.memo,
            pid: fields.pid,
            create_time: fields.create_time,
            menid: fields.menid,
            htmlid: fields.htmlid,
            levelcode: fields.levelcode,
            leaftype: fields.leaftype,
            cls: fields.cls,
        },
    });

    message.success('添加成功');
    this.handleModalVisible();

};


handleDeleteRecord = record => {
        const { dispatch } = this.props;

        dispatch({
        	type: 'proresourceaction/delete_by_primarykey_for_proresourceaction',
       		payload: {
        		recordid: record.id,
        	},
	        callback: () => {
		        this.setState({
		        	selectedRows: [],
		        });
	        },
        });

        message.success('删除成功');


};

handleUpdate = fields => {

    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
        type: 'proresourceaction/update_for_proresourceaction',
        payload: {
                id: fields.id,
                name: fields.name,
                enname: fields.enname,
                handler: fields.handler,
                icon: fields.icon,
                status: fields.status,
                orderid: fields.orderid,
                memo: fields.memo,
                pid: fields.pid,
                create_time: fields.create_time,
                menid: fields.menid,
                htmlid: fields.htmlid,
                levelcode: fields.levelcode,
                leaftype: fields.leaftype,
                cls: fields.cls,
        },
    });

    message.success('修改成功');
    this.handleUpdateModalVisible();

};

renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
	        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
			        <FormItem label="操作名称">
				        {getFieldDecorator('name')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
		    <Col md={8} sm={24}>
		        <FormItem label="英文名称">
		        	{getFieldDecorator('enname')(<Input placeholder="请输入" />)}
				</FormItem>
		    </Col>
		    <Col md={8} sm={24}>
		        <span className={styles.submitButtons}>
			        <Button type="primary" htmlType="submit">
			        	查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        	重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        	展开 <Icon type="down" />
			        </a>
		        </span>
	        </Col>
	        </Row>
        </Form>
);
}

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
        <FormItem label="操作名称">
        {getFieldDecorator('name')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="英文名称">
        {getFieldDecorator('enname')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="操作方法">
        {getFieldDecorator('handler')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    </Row>
    <div style={{ overflow: 'hidden' }}>
<div style={{ marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        收起 <Icon type="up" />
        </a>
        </div>
        </div>
        </Form>
);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            proresourceaction: { data },
            loading,
        } = this.props;



        const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues  } = this.state;

        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
        };
        const updateMethods = {
            handleUpdateModalVisible: this.handleUpdateModalVisible,
            handleUpdate: this.handleUpdate,
        };
        const viewMethods = {
            handleViewModalVisible: this.handleViewModalVisible
        };
        return (
            <PageHeaderWrapper title="按钮资源信息列表">
            <Card bordered={false}>
            <div className={styles.proResourceActiontableList}>
            <div className={styles.proResourceActiontableListForm}>{this.renderForm()}</div>
            <div className={styles.proResourceActiontableListOperator}>
    </div>
        <StandardTable
        rowKey={"id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>

        <ProResourceActionCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <ProResourceActionUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ProResourceActionViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
    }
}

export default ProResourceActionList;
